package com.msb.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.constant.WareConstant;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.mall.ware.dao.PurchaseDao;
import com.msb.mall.ware.entity.PurchaseDetailEntity;
import com.msb.mall.ware.entity.PurchaseEntity;
import com.msb.mall.ware.service.PurchaseDetailService;
import com.msb.mall.ware.service.PurchaseService;
import com.msb.mall.ware.service.WareSkuService;
import com.msb.mall.ware.vo.MergeVO;
import com.msb.mall.ware.vo.PurchaseDoneVO;
import com.msb.mall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        // 查询新建和已分配状态的需求但
        wrapper.eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode())
                .or().eq("status", WareConstant.PurchaseStatusEnum.ASSIGED.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 完成采购需求的合单操作
     *
     * @param mergeVO
     * @return
     */
    @Transactional
    @Override
    public int merge(MergeVO mergeVO) {
        // 查询采购需求单
        List<PurchaseDetailEntity> collect = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>()
                        .in("id", mergeVO.getItems()))
                .stream().filter(detail -> detail.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                        detail.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode())
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            return -1;
        }
        Long purchaseId = mergeVO.getPurchaseId();
        // 采购单不存在就创建
        if (purchaseId == null) {
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            this.save(purchase);
            purchaseId = purchase.getId();
        }
        // 整合菜单需求单
        final Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> list = collect.stream().map(detail -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setId(detail.getId());
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(list);
        // 更新采购单的更新时间
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(purchaseId);
        entity.setUpdateTime(new Date());
        this.updateById(entity);
        return 1;
    }

    @Override
    @Transactional
    public void receive(List<Long> ids) {
        // 只有状态是新建和已分配状态的采购单才可以领取
        List<PurchaseEntity> list = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(purchaseEntity -> {
            if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {
                return true;
            }
            return false;
        }).map(entity -> {
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setId(entity.getId());
            purchase.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            purchase.setUpdateTime(new Date());
            return purchase;
        }).collect(Collectors.toList());
        // 更新采购单的状态（已领取）和时间
        this.updateBatchById(list);
        // 根据采购单id，查询关联其的采购项
        for (Long id : ids) {
            // 更新采购需求项的状态（正在采购）和时间
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetailByPurchaseId(id);
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
                purchaseDetail.setId(entity.getId());
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetail;
            }).collect(Collectors.toList());
            // 批量更新采购项
            purchaseDetailService.updateBatchById(collect);
        }
    }

    /**
     * 采购完成
     *
     * 采购完成之后，需要把数量加到对应的库存中（完成入库操作）
     *
     * @param vo
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVO vo) {
        // 改变采购单状态。采购单关联的采购项必须全部是已完成，采购单的状态才是已完成。
        List<PurchaseItemDoneVO> items = vo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        Boolean hasError = false;
        for (PurchaseItemDoneVO item : items) {
            if (item.getStatus() == null) {
                continue;
            }
            PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
            purchaseDetail.setId(item.getItemId());
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                hasError = true;
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            } else {
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 查询库存等信息
                PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(purchaseDetail.getId());
                wareSkuService.addStock(purchaseDetailEntity.getSkuId(), purchaseDetailEntity.getWareId(),
                        purchaseDetailEntity.getSkuNum());
            }
            purchaseDetailEntities.add(purchaseDetail);
        }

        // 批量更新操作
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        // 更新采购单状态
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(vo.getId());
        purchase.setStatus(hasError ? WareConstant.PurchaseStatusEnum.HASERROR.getCode() : WareConstant.PurchaseStatusEnum.FINISHED.getCode());
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);
    }
}